<template>
  <HeaderComponent class="header" />
  <div class="container">
    <!-- 发布新鲜事部分 -->
    <div class="create-post">
      <textarea
          @click="openModal"
          placeholder="有什么美食攻略想告诉大家？"
          readonly
      ></textarea>
    </div>

    <!-- 模态框 -->
    <div v-if="isModalOpen" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>发布新鲜事</h3>
          <button @click="closeModal" class="close-button">&times;</button>
        </div>
        <div class="modal-content">
          <input
              v-model="PostDTO.title"
              placeholder="帖子标题..."
              class="title-input"
          />
          <textarea
              v-model="PostDTO.content"
              placeholder="写下你想分享的内容..."
          ></textarea>
          <input
              type="file"
              @change="handleImageUpload"
              accept="image/*"
              class="file-input"
          />
          <div v-if="imagePreview" class="image-preview">
            <img :src="imagePreview" alt="预览图片"  style="width: 200px; height: 200px; border-radius: 4px; margin-top: 10px;" />
            <button @click="removeImage" class="remove-image-button">移除图片</button>
          </div>
        </div>
        <div class="modal-actions">
          <button @click="publishPost" class="publish-button">发布</button>
        </div>
      </div>
    </div>

    <!-- 动态帖子列表 -->
    <div v-for="post in posts" :key="post.id" class="post">
      <div class="post-header">
        <div class="username">{{ post.userName }}</div>
        <div class="time">{{ formatDate(post.date) }}</div>
      </div>
      <div class="post-content">{{ post.content }}</div>
      <div v-if="post.image" class="post-image">
        <img :src="require(`../assets/uploads/${post.image}`)" alt="帖子图片"
             style="width: 50%; height: auto; border-radius: 4px; margin-top: 10px;" />
      </div>
      <!-- 点赞按钮和点赞数量 -->
      <div class="like-section">
        <!-- 点赞图标 -->
        <div class="like-icon-container">
          <img
              @click="toggleLike(post)"
              :src="post.isLike === 1 ?
          require('../assets/thumbs-uped.svg') : require('../assets/thumbs-up.svg')"
              alt="点赞图标"
              :class="{ 'like-animation': post.isAnimating }"
          >
          <!--        {{ isLiked ? '取消点赞' : '点赞' }}-->
          <!-- 粒子效果容器 -->
          <div class="particle-container" v-if="post.isAnimating">
            <div
                v-for="(particle, index) in post.particles"
                :key="index"
                class="particle"
                :style="{
              '--x': `${particle.x}px`,
              '--y': `${particle.y}px`,
              top: '50%',
              left: '50%',
            }"
            ></div>
          </div>
        </div>
        <span class="like-count">{{ post.likes || 0 }}</span>
      </div>
<!--      <span class="like-count">-->
<!--        <img-->
<!--            src="../assets/thumbs-up.svg"-->
<!--             alt="点赞图标" style="width: 20px; height: 20px; margin-right: 5px;" />-->
<!--        {{ post.likes || 0 }}-->
<!--      </span>-->
      <div class="post-actions">
        <div class="action" @click="viewPost(post.id)">查看详情</div>
      </div>
    </div>
  </div>
</template>

<script>
import {onMounted, reactive, ref} from 'vue';
import HeaderComponent from "@/components/HeaderComponent.vue";
import {AddPost, GetPosts, isLike, likePost} from "@/api";
import {ElMessage} from "element-plus";
import router from "@/router";

export default {
  name: 'CommunityComponent',
  components: {
    HeaderComponent,
  },
  setup() {
    const isModalOpen = ref(false);
    const newPostTitle = ref('');
    const newPostContent = ref('');
    const imageFile = ref(null);
    const imagePreview = ref('');
    const isLiked = ref(false); // 当前用户是否已经点赞
    const isAnimating = ref(false); // 控制动画状态
    const particles = ref([]); // 粒子效果数据
    const posts = ref([]);
    // const isLiked = ref(false); // 当前用户是否已经点赞


    const PostDTO = reactive(
        {
          title: '',
          content: '',
          image: '',
        }
    )

    // 获取帖子信息
    const fetchPosts = async () => {
      try {
        const response = await GetPosts();
        console.log('GetPosts Response:', response); // 添加调试信息
        if (response.data.code === 200) {
          posts.value = response.data.data.map(post => ({
            ...post,
            isAnimating: false,
            particles: []
          }));
        } else {
          ElMessage.error("获取帖子信息失败");
        }
      } catch (error) {
        console.error("获取帖子信息失败:", error);
        ElMessage.error("请求失败，请稍后重试");
      }
    };

    // 点赞或取消点赞
    const toggleLike = async (post) => {
      try {
        const response = await likePost(post.id);
        if (response.data.code === 200) {
          // await fetchPosts();
          // isLiked.value = !isLiked.value; // 切换点赞状态
          await checkIfLiked(post.id);
          // post.value.likes += isLiked.value ? 1 : -1; // 更新点赞数量
          // ElMessage.success(isLiked.value ? "点赞成功" : "取消点赞成功");

          // 触发点赞动画
          post.isAnimating = true;
          generateParticles(post);
          setTimeout(() => {
            post.isAnimating = false;
            post.particles = [];
          }, 1000); // 动画持续 1 秒
          // 然后获取最新数据
          await fetchPosts();
        } else {
          ElMessage.error("操作失败");
        }
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    };
    // 检查当前用户是否已经点赞
    const checkIfLiked = async (postId) => {
      try {
        const response = await isLike(postId);
        if (response.data.code === 200) {
          if (response.data.data === "1"){
            isLiked.value = true;
          }else{
            isLiked.value = false;
          }
          // isLiked.value = response.data.data === "1"; // "1" 表示已点赞
        }
        console.log('response',response)
      } catch (error) {
        console.error("检查点赞状态失败:", error);
      }
    };
    // 生成粒子效果
    const generateParticles = (post) => {
      const particleCount = 10;
      const newParticles = [];
      for (let i = 0; i < particleCount; i++) {
        const angle = (Math.random() * 360) * (Math.PI / 180);
        const distance = Math.random() * 50 + 50;
        newParticles.push({
          x: Math.cos(angle) * distance,
          y: Math.sin(angle) * distance,
        });
      }
      post.particles = newParticles;
    };
    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleString();
    };

    // // 检查当前用户是否已经点赞
    // const checkIfLiked = async (postId) => {
    //   try {
    //     const response = await isLike(postId);
    //     if (response.data.code === 200) {
    //       if (response.data.data === "1"){
    //         isLiked.value = true;
    //       }else{
    //         isLiked.value = false;
    //       }
    //       // isLiked.value = response.data.data === "1"; // "1" 表示已点赞
    //     }
    //     console.log('response',response)
    //   } catch (error) {
    //     console.error("检查点赞状态失败:", error);
    //   }
    // };
    const openModal = () => {
      isModalOpen.value = true;
    };

    const closeModal = () => {
      isModalOpen.value = false;
      newPostContent.value = '';
      imageFile.value = null;
      imagePreview.value = '';
    };

    const handleImageUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        imageFile.value = file;
        imagePreview.value = URL.createObjectURL(file);
      }
    };

    const removeImage = () => {
      imageFile.value = null;
      imagePreview.value = '';
    };

    const publishPost = async () => {
      if(!PostDTO.title){
        ElMessage.error("请填写标题");
        return;
      }
      // if(!PostDTO.content){
      //   ElMessage.error("请填写内容");
      //   return;
      // }
      if (!newPostContent.value.trim() && !imageFile.value) {
        ElMessage.error("请填写内容或上传图片");
        return;
      }

      // 创建 FormData 对象
      const formData = new FormData();
      formData.append('title', PostDTO.title); // 添加标题
      formData.append('content', PostDTO.content); // 添加内容
      if (imageFile.value) {
        formData.append('file', imageFile.value); // 添加文件
      }

      try {
        const response = await AddPost(formData);
        // // 打印 formData 以确保包含所有字段
        // formData.forEach((value, key) => {
        //   console.log(key, value);
        // });
        console.log('AddPost Response:', response); // 添加调试信息
        if (response.data.code === 200) {
          ElMessage.success("帖子发布成功");
          setTimeout(() => {
            // 更新帖子列表
            fetchPosts();
          }, 1500)
          closeModal();
        } else {
          ElMessage.error("发布帖子失败");
        }
      } catch (error) {
        console.error("发布帖子失败:", error);
        ElMessage.error("请求失败，请稍后重试");
      }
    };

    const viewPost = async (postId) => {
      await router.push({
        name: 'PostInfo',
        params: {
          postId: postId,
        },
      });
    };

    // 页面加载时获取帖子信息
    onMounted(() => {
      fetchPosts();
      // checkIfLiked();
    });

    return {
      posts,
      fetchPosts,
      formatDate,
      isModalOpen,
      newPostContent,
      newPostTitle,
      imagePreview,
      openModal,
      closeModal,
      handleImageUpload,
      removeImage,
      publishPost,
      viewPost,
      PostDTO,
      toggleLike,
      isLiked,
      checkIfLiked,
      isAnimating,
      generateParticles,
      particles,
      // checkIfLiked,
    };
  },
};
</script>

<style scoped>
.header {
  margin-bottom: 80px;
}

.container {
  max-width: 600px;
  margin: 0 auto;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.like-count{
  display: flex;
  align-items: center;
  gap: 5px; /* 图标和数字之间的间距 */
  font-size: 14px;
  color: #333;
}

.create-post textarea {
  width: 95%;
  height: 30px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  cursor: pointer;
  margin-bottom: 20px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal {
  background-color: #fff;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  padding: 20px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.modal-header h3 {
  margin: 0;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
}

.modal-content textarea {
  width: 95%;
  height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  margin-bottom: 10px;
}

.file-input {
  margin-bottom: 10px;
}

.image-preview {
  position: relative;
  margin-bottom: 10px;
}

.image-preview img {
  width: 100%;
  border-radius: 4px;
}

.remove-image-button {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
}

.publish-button {
  padding: 8px 16px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.publish-button:hover {
  background-color: #0056b3;
}

.post {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.post:last-child {
  border-bottom: none;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.post-header .username {
  font-weight: bold;
  color: #333;
}

.post-header .time {
  font-size: 12px;
  color: #999;
  margin-left: auto;
}

.post-content {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.post-image img {
  width: 100%;
  border-radius: 4px;
  margin-top: 10px;
}

.post-actions {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.post-actions .action {
  margin-right: 20px;
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.post-actions .action:hover {
  color: #333;
}


.like-section {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.like-count {
  font-size: 14px;
  color: #333;
}


/* 点赞图标的动画 */
@keyframes likeAnimation {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.5);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 点赞图标点击时的特效 */
.like-animation {
  animation: likeAnimation 0.5s ease-in-out;
}

/* 点赞图标容器 */
.like-icon-container {
  position: relative; /* 设置为相对定位，粒子效果容器将相对于此定位 */
  display: inline-block; /* 确保容器大小与图标一致 */
}

/* 粒子效果容器 */
.particle-container {
  position: absolute; /* 绝对定位，相对于 like-icon-container */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none; /* 防止粒子效果容器拦截点击事件 */
}

/* 粒子效果 */
.particle {
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: #4d636a; /* Bilibili 主题色 */
  border-radius: 50%;
  animation: particleAnimation 1s ease-out;
  transform: translate(var(--x), var(--y)); /* 使用 CSS 变量控制粒子位置 */
}

@keyframes particleAnimation {
  0% {
    transform: translate(0, 0) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(var(--x), var(--y)) scale(0);
    opacity: 0;
  }
}
</style>
